<?php
namespace jy_area9fan;
defined('BY_JYA') or exit('error');
/*
	区域代理分红计算
	
*/
class commission extends \plugin{
	/*
		生成佣金
	*/
	function create($order){
		$isopen=intval($this->setting['isopen']);
		if(!$isopen){
			return;
		}
		$this->model('member')->update_agent_level($order['mid']);
		$this->order=$order;
        //获取地址
        $order['address']=json_decode($order['address'],true);
        if($order['address'] && ($order['address']['name'] || $order['address']['adddress'])){
            $address=$order['address'];
        }else{
            $address=pdo_get('core_address',array('uniacid'=>$_SESSION['uniacid'],'id'=>$order['addressid']),'pcd');
        }
		$address=$address['pcd'];
        if(!is_array($address)){
            $address=json_decode($address,true);
        }
		$this->commission_order=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$this->order['mid'],
			'ordersn'=>$this->order['ordersn'],
			'order_price'=>$this->order['price'],
			'commission_money'=>0,
			'xuni_money'=>0,
			'createtime'=>TIMESTAMP,
		);
		//佣金计算方式，是否扣除运费
		if($this->setting['commissiontype']==1){
			$this->commission_order['commission_price']=$this->order['price'];
		}else{
			$this->commission_order['commission_price']=$this->order['price']-$this->order['dispatchprice'];
		}
		//直荐分润,间荐分润,次荐奖积分
		$fromuser=pdo_getcolumn('core_members',array('id'=>$this->order['mid'],'uniacid'=>$_SESSION['uniacid']),'fromuser');
		for($i=0;$i<3;$i++){
			if(!$fromuser){
				break;
			}
			$agent_area=$this->get('agent_area',array('mid'=>$fromuser,'uniacid'=>$_SESSION['uniacid']));
			if($agent_area['status'] && $agent_area['level_id']){
				$this->create_commission($agent_area,$i);
			}
			$fromuser=pdo_getcolumn('core_members',array('id'=>$fromuser,'uniacid'=>$_SESSION['uniacid']),'fromuser');
		}
		if($address){
			//计算省级代理分红
			$this->province_commission($address);
			$this->city_commission($address);
			$this->district_commission($address);
			$this->street_commission($address);
		}
		//商户流水分红
		$install = $this->plugin_exists('jy_merch');
		if($install){
			$merchmid=pdo_getcolumn('jy_merch_user',array('id'=>$this->order['merchid'],'uniacid'=>$_SESSION['uniacid']),'mid');
			$fromuser=pdo_getcolumn('core_members',array('id'=>$merchmid,'uniacid'=>$_SESSION['uniacid']),'fromuser');
			for($i=0;$i<3;$i++){
				if(!$fromuser){
					break;
				}
				$agent_area=$this->get('agent_area',array('mid'=>$fromuser,'uniacid'=>$_SESSION['uniacid']));
				if($agent_area['status'] && $agent_area['level_id']){
					$this->create_commission($agent_area,$i,'',true);
				}
				$fromuser=pdo_getcolumn('core_members',array('id'=>$fromuser,'uniacid'=>$_SESSION['uniacid']),'fromuser');
			}
		}
		//生成分销订单
		if($this->commission_order['isarea']){
			$indata=$this->commission_order;
			unset($indata['isarea']);
			$this->insert('order',$indata);
		}
		return true;
	}
	public function province_commission($address){
		$area_code=pdo_getcolumn('core_area',array('address'=>$address['province']),'code');
		$this->commission_order['area_code']=$area_code;
		$agents=$this->getall('agent_area',array('level_id'=>9,'uniacid'=>$_SESSION['uniacid'],'status'=>1,'area_code'=>$area_code));
		if(!$agents){
			return;
		}
		foreach($agents as $agent){
			$member=$this->get('member',array('mid'=>$agent['mid']));
			if(!$member || $member['stop']){
				continue;
			}
			$this->create_commission($agent,1,true);
		}
	}
	public function city_commission($address){
		if(!$address['city']){
			return;
		}
		$area_code=pdo_getcolumn('core_area',array('address'=>$address['province'].' '.$address['city']),'code');
		$this->commission_order['area_code']=$area_code;
		$agents=$this->getall('agent_area',array('level_id'=>8,'uniacid'=>$_SESSION['uniacid'],'status'=>1,'area_code'=>$area_code));
		if(!$agents){
			return;
		}
		foreach($agents as $agent){
			$member=$this->get('member',array('mid'=>$agent['mid']));
			if(!$member || $member['stop']){
				continue;
			}
			$this->create_commission($agent,2,true);
		}
	}
	public function district_commission($address){
		if(!$address['district']){
			return;
		}
		$area_code=pdo_getcolumn('core_area',array('address'=>$address['province'].' '.$address['city'].' '.$address['district']),'code');
		$this->commission_order['area_code']=$area_code;
		$agents=$this->getall('agent_area',array('level_id'=>7,'uniacid'=>$_SESSION['uniacid'],'status'=>1,'area_code'=>$area_code));
		if(!$agents){
			return;
		}
		foreach($agents as $agent){
			$member=$this->get('member',array('mid'=>$agent['mid']));
			if(!$member || $member['stop']){
				continue;
			}
			$this->create_commission($agent,3,true);
		}
	}
	public function street_commission($address){
		if(!$address['street']){
			return;
		}
		$area_code=pdo_getcolumn('core_area',array('address'=>$address['province'].' '.$address['city'].' '.$address['district'].' '.$address['street']),'code');
		$this->commission_order['area_code']=$area_code;
		$agents=$this->getall('agent_area',array('level_id'=>6,'uniacid'=>$_SESSION['uniacid'],'status'=>1,'area_code'=>$area_code));
		if(!$agents){
			return;
		}
		foreach($agents as $agent){
			$member=$this->get('member',array('mid'=>$agent['mid']));
			if(!$member || $member['stop']){
				continue;
			}
			$this->create_commission($agent,4,true);
		}
	}
	/*
		给指定区域代理计算分红
	*/
	function create_commission($agent,$i,$isarea=false,$ismerch=false){
		$fenset=$this->setting['fenset'];
		foreach($fenset as $fv){
			if($agent['level_id']==$fv['key']){
				$feeinfo=$fv;
				$feerate=$fv['feerate'];
				$tuifee0=$fv['tuifee0'];
				$tuifee1=$fv['tuifee1'];
				$jifen2=$fv['jifen2'];
				$mtuifee0=$fv['mtuifee0'];
				$mtuifee1=$fv['mtuifee1'];
				$mjifen2=$fv['mjifen2'];
				break;
			}
		}
		$order_price=$this->order['price'];
		$fee=0;
		$tuifee0fee=0;
		$tuifee1fee=0;
		$jifen=0;
		$mtuifee0fee=0;
		$mtuifee1fee=0;
		$mjifen=0;
		$this->needorder=false;
        $total_lastcostprice=0;
		foreach($this->order['goods'] as $goods){
					if(!$goods['fee_desc'] && $goods['merchid']){
						model('jy_weishop/order')->setfee_desc($goods['orderid']);
					}
					$total_price=$goods['total_price']?:pdo_getcolumn('jy_weishop_order_goods',array('id'=>$goods['id']),'total_price');
					$costprice=pdo_getcolumn('jy_weishop_goods',array('id'=>$goods['goodsid']),'costprice');
					$total_costprice=$goods['total']*$costprice;
					$total_lastcostprice +=$total_costprice;
					$goods_commission=$this->get('goods',array('goods_id'=>$goods['goodsid']));
					if(!$goods_commission['id']){
						$this->needorder=true;
						continue;
					}
					if($goods_commission['ignore']){
						$order_price=$order_price-$goods['total_price'];
						continue;
					}
					//如果商品单独设置佣金，将减少本商品的金额
					$order_price=$order_price-$total_price;
					$goods_commission['commissions']=$goods_commission['commissions']?json_decode($goods_commission['commissions'],true):array();
					foreach($goods_commission['commissions'] as $gc){
						if($gc['level_id']==0){
							$demogoodsfeerate=$gc['feerate'];
							$demogoodstuifee0=$gc['tuifee0'];
							$demogoodstuifee1=$gc['tuifee1'];
							$demogoodsjifen2=$gc['jifen2'];
							$demogoodsmtuifee0=$gc['mtuifee0'];
							$demogoodsmtuifee1=$gc['mtuifee1'];
							$demogoodsmjifen2=$gc['mjifen2'];
						}
						if($gc['level_id']!=$agent['level_id']){
							continue;
						}else{
							$goodsfeerate=$gc['feerate'];
							$goodstuifee0=$gc['tuifee0'];
							$goodstuifee1=$gc['tuifee1'];
							$goodsjifen2=$gc['jifen2'];
							$goodsmtuifee0=$gc['mtuifee0'];
							$goodsmtuifee1=$gc['mtuifee1'];
							$goodsmjifen2=$gc['mjifen2'];
							break;
						}
					}
					$goodsfeerate=$goodsfeerate?:$demogoodsfeerate;
					$goodstuifee0=$goodstuifee0?:$demogoodstuifee0;
					$goodstuifee1=$goodstuifee1?:$demogoodstuifee1;
					$goodsjifen2=$goodsjifen2?:$demogoodsjifen2;
                    $mgoodstuifee0=$goodsmtuifee0?:$demogoodsmtuifee0;
                    $mgoodstuifee1=$goodsmtuifee1?:$demogoodsmtuifee1;
                    $mgoodsjifen2=$goodsmjifen2?:$demogoodsmjifen2;
					//利润计算
					if($this->setting['commissionfeetype']==2){
							$total_price -=$total_costprice;
							$total_lastcostprice -=$total_costprice;
					}
					if(substr($goodsfeerate,-1)=='%'){
						$fee+=($total_price*substr($goodsfeerate,0,-1))/100;
					}else{
						$fee+=$goodsfeerate*$goods['total'];
					}
					if(substr($goodstuifee0,-1)=='%'){
						$tuifee0fee+=($total_price*substr($goodstuifee0,0,-1))/100;
					}else{
						$tuifee0fee+=$goodstuifee0*$goods['total'];
					}
					if(substr($goodstuifee1,-1)=='%'){
						$tuifee1fee+=($total_price*substr($goodstuifee1,0,-1))/100;
					}else{
						$tuifee1fee+=$goodstuifee1*$goods['total'];
					}
					if(substr($goodsjifen2,-1)=='%'){
						$jifen+=($total_price*substr($goodsjifen2,0,-1))/100;
					}else{
						$jifen+=$goodsjifen2*$goods['total'];
					}
					//商户
					if($ismerch){
						if(substr($mgoodstuifee0,-1)=='%'){
							$mtuifee0fee+=($total_price*substr($mgoodstuifee0,0,-1))/100;
						}else{
							$mtuifee0fee+=$mgoodstuifee0*$goods['total'];
						}
						if(substr($mgoodstuifee1,-1)=='%'){
							$mtuifee1fee+=($total_price*substr($mgoodstuifee1,0,-1))/100;
						}else{
							$mtuifee1fee+=$mgoodstuifee1*$goods['total'];
						}
						if(substr($mgoodsjifen2,-1)=='%'){
							$mjifen+=($total_price*substr($mgoodsjifen2,0,-1))/100;
						}else{
							$mjifen+=$mgoodsjifen2*$goods['total'];
						}
					}
		}
		if($this->needorder && $order_price>0){
					if(substr($feerate,-1)=='%'){
						$fee+=($total_price*substr($feerate,0,-1))/100;
					}else{
						$fee+=$feerate*$goods['total'];
					}
					if(substr($tuifee0,-1)=='%'){
						$tuifee0fee+=($total_price*substr($tuifee0,0,-1))/100;
					}else{
						$tuifee0fee+=$tuifee0*$goods['total'];
					}
					if(substr($tuifee1,-1)=='%'){
						$tuifee1fee+=($total_price*substr($tuifee1,0,-1))/100;
					}else{
						$tuifee1fee+=$tuifee1*$goods['total'];
					}
					if(substr($jifen2,-1)=='%'){
						$jifen+=($total_price*substr($jifen2,0,-1))/100;
					}else{
						$jifen+=$jifen2*$goods['total'];
					}
					if($ismerch){
						if(substr($mtuifee0,-1)=='%'){
							$mtuifee0fee+=($total_price*substr($mtuifee0,0,-1))/100;
						}else{
							$mtuifee0fee+=$mtuifee0*$goods['total'];
						}
						if(substr($mtuifee1,-1)=='%'){
							$mtuifee1fee+=($total_price*substr($mtuifee1,0,-1))/100;
						}else{
							$mtuifee1fee+=$mtuifee1*$goods['total'];
						}
						if(substr($mjifen2,-1)=='%'){
							$mjifen+=($total_price*substr($mjifen2,0,-1))/100;
						}else{
							$mjifen+=$mjifen2*$goods['total'];
						}
					}
		}
		//区域分润
		if($fee>0 && $isarea){
				$this->commission_order['commission_money']+=$fee;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$agent['mid'],
					'agent_id'=>$agent['id'],
					'area_code'=>$agent['area_code'],
					'level'=>1,
					'ordersn'=>$this->order['ordersn'],
					'money'=>$fee,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'status'=>$this->setting['is_jiesuan']?:0,
				);
				$this->insert('commission',$new_commission);
		}
		//直荐分润
		if($tuifee0fee>0 && !$i && !$isarea){
				$this->commission_order['commission_money']+=$tuifee0fee;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$agent['mid'],
					'agent_id'=>$agent['id'],
					'area_code'=>$agent['area_code'],
					'level'=>2,
					'ordersn'=>$this->order['ordersn'],
					'money'=>$tuifee0fee,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'status'=>$this->setting['is_jiesuan']?:0,
				);
				$this->insert('commission',$new_commission);
		}
		//间荐分润
		if($tuifee1fee>0 && $i==1 && !$isarea){
				$this->commission_order['commission_money']+=$tuifee1fee;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$agent['mid'],
					'agent_id'=>$agent['id'],
					'area_code'=>$agent['area_code'],
					'level'=>3,
					'ordersn'=>$this->order['ordersn'],
					'money'=>$tuifee1fee,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'status'=>$this->setting['is_jiesuan']?:0,
				);
				$this->insert('commission',$new_commission);
		}
		//次荐奖积分
		if($jifen>0 && $i==2 && !$isarea){
				$this->commission_order['xuni_money']+=$jifen;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$agent['mid'],
					'agent_id'=>$agent['id'],
					'area_code'=>$agent['area_code'],
					'level'=>4,
					'ordersn'=>$this->order['ordersn'],
					'xuni_money'=>$jifen,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'status'=>$this->setting['is_jiesuan']?:0,
				);
				$this->insert('commission',$new_commission);
		}
		//商户直荐分润
		if($mtuifee0fee>0 && !$i && $ismerch){
				$this->commission_order['commission_money']+=$mtuifee0fee;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$agent['mid'],
					'agent_id'=>$agent['id'],
					'area_code'=>$agent['area_code'],
					'level'=>5,
					'ordersn'=>$this->order['ordersn'],
					'money'=>$mtuifee0fee,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'status'=>$this->setting['is_jiesuan']?:0,
				);
				$this->insert('commission',$new_commission);
		}
		//商户间荐分润
		if($mtuifee1fee>0 && $i==1 && $ismerch){
				$this->commission_order['commission_money']+=$mtuifee1fee;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$agent['mid'],
					'agent_id'=>$agent['id'],
					'area_code'=>$agent['area_code'],
					'level'=>6,
					'ordersn'=>$this->order['ordersn'],
					'money'=>$mtuifee1fee,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'status'=>$this->setting['is_jiesuan']?:0,
				);
				$this->insert('commission',$new_commission);
		}
		//商户次荐奖积分
		if($mjifen>0 && $i==2 && $ismerch){
				$this->commission_order['xuni_money']+=$mjifen;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$agent['mid'],
					'agent_id'=>$agent['id'],
					'area_code'=>$agent['area_code'],
					'level'=>7,
					'ordersn'=>$this->order['ordersn'],
					'xuni_money'=>$mjifen,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'status'=>$this->setting['is_jiesuan']?:0,
				);
				$this->insert('commission',$new_commission);
		}
			//判断是否存在区域代理
			$this->commission_order['isarea']=true;
			//此处判断分销商是否满足升级条件，如果满足则升级分销商等级
			$agent_update=array(
				'order_price +='=>$this->commission_order['order_price'],
				'order_num +='=>1,
			);
			$this->update('agent_area',$agent_update,array('id'=>$agent['id']));
	}
	/*
		订单完成时，把佣金状态由初始的订单待完成升级为待结算
	*/
	public function order_complete($order){
		$this->update('commission',array('status'=>1,'complete_time'=>TIMESTAMP),array('status'=>0,'ordersn'=>$order['ordersn']));
	}
	/*
		创建结算单
	*/
	public function create_balance($mid){
		if(!$mid){
			exi('请先选择要结算的会员！','error');
		}
		//获取可结算佣金
		$params=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'status'=>1);
		if($this->setting['balance_day']){
			//结算天数
			$time=TIMESTAMP-intval($this->setting['balance_day'])*86400;
			$params['complete_time <']=$time;
		}
		$commissions=$this->getall('commission',$params);
		if(!$commissions){
			exi('没有可结算的佣金！','error');
		}
		$commission_num=count($commissions);
		$money=0;
		foreach($commissions as $commission){
			$money+=$commission['money'];
		}
		//结算最低佣金检测
		if($money<$this->setting['balance_money']){
			exi('可结算佣金太少，无法结算！','error');
		}
		$new_balance=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$mid,
			'balancesn'=>get_ordersn($this->tablename('commission'),'balancesn','AC'),
			'commission_num'=>$commission_num,
			'money'=>$money,
			'createtime'=>TIMESTAMP,
			'status'=>0,
		);
		//结算手续费
		if($this->setting['balance_per']){
			$new_balance['balance_pay']=intval($new_balance['money']*$this->setting['balance_per'])/100;
		}else{
			$new_balance['balance_pay']=0;
		}
		$new_balance['final_money']=$new_balance['money']-$new_balance['balance_pay'];
		$this->insert('balance',$new_balance);
		$balance_id=pdo_insertid();
		foreach($commissions as $commission){
			$update=array(
				'status'=>2,
				'balancesn'=>$new_balance['balancesn'],
			);
			$this->update('commission',$update,array('id'=>$commission['id']));
		}
		if($post['pay_type']=='credit'){
			$typetitle='余额';
		}
		if($post['pay_type']=='wechat'){
			$typetitle='微信';
		}
		$this->model('notice')->notice_fenxiao_tixian($mid,$money,$typetitle);
		return $balance_id;
	}
	/*
		审核结算单
	*/
	public function check_balance($balance_id,$status,$remark=''){
		$update=array(
			'status'=>$status,
			'check_time'=>TIMESTAMP,
			'remark'=>$remark,
		);
		$this->update('balance',$update,array('id'=>$balance_id));
	}
	/*
		打款结算单
	*/
	public function pay_balance($balance_id,$pay_type){
		$balance=$this->get('balance',array('id'=>$balance_id,'uniacid'=>$_SESSION['uniacid']));
		if(!$balance || $balance['status']!=1){
			exi('结算单不存在或者不符合打款条件，打款失败！','error');
		}
		$pay_types=array_keys($this->pay_types);
		if(!$pay_type || !in_array($pay_type,$pay_types)){
			exi('未设置打款方式或者打款方式不合法，打款失败！','error');
		}
		$func_name='pay_balance_by_'.$pay_type;
		$trade_no=$this->$func_name($balance['mid'],$balance['final_money'],$balance['balancesn']);
		$update=array(
			'status'=>3,
			'pay_type'=>$pay_type,
			'pay_trade_no'=>$trade_no,
			'pay_time'=>TIMESTAMP,
		);
		$this->update('balance',$update,array('id'=>$balance['id']));
		$this->model('notice')->notice_fenxiao_dakuan($balance['mid'],$balance['final_money']);
		return true;
	}
	/*
		打款到余额
	*/
	protected function pay_balance_by_credit($mid,$money,$balancesn){
		return cfc('core')->member_credit($mid,'credit2',$money,true,$this->plugin_name,$remark='分销佣金打款');
	}
	/*
		打款到微信零钱
	*/
	protected function pay_balance_by_wechat($mid,$money,$balancesn){
		$params=array(
			'openid'=>$mid,
			'mch_billno'=>$balancesn,
			'money'=>$money,
			'remark'=>'代理商佣金发放',
		);
		$res=cfc('wechat_pay')->mch_pay($params);
		return $res['payment_no'];
	}
	/*
		打款到支付宝
	*/
	protected function pay_balance_by_alipay($mid,$money,$balancesn){
		exi('暂不支持打款到支付宝！','error');
	}
	/*
		打款到银行账户
	*/
	protected function pay_balance_by_union($mid,$money,$balancesn){
		exi('暂不支持打款到银行账户！','error');
	}

	public function commission_remark($remark){
		if(!$remark){
			return '';
		}
		$remark=json_decode($remark,true);
		$goods_str='';
		if($remark['goods_commission']){
			foreach($remark['goods_commission'] as $goods){
				$goods['title']=pdo_getcolumn('jy_weishop_goods',array('id'=>$goods['goods_id']),'title');
				$goods_str.="商品ID【{$goods['goods_id']}】，商品名称【{$goods['title']}】，商品数量【{$goods['total']}】，商品总价【{$goods['total_price']}】，佣金规则【{$goods['commission_per']}】，分销佣金【{$goods['commission_money']}】\n";
			}
		}else{
			$goods_str='';
		}
		$remark['level_title']=pdo_getcolumn('jy_area9fan_level',array('uniacid'=>$_SESSION['uniacid'],'level'=>$remark['level_id']),'title');
		$remark['level_title']=$remark['level_title']?:'默认等级';
		$remark_str=<<<TPL
分销商等级ID【{$remark['level_id']}】，等级名称【{$remark['level_title']}】，佣金等级【{$remark['commission_level']}】，订单总价【{$remark['order_price']}】
商品独立佣金：
{$goods_str}
订单佣金：
除去设置独立佣金的商品外订单金额【{$remark['order_commission']['order_price']}】，佣金规则【{$remark['order_commission']['commission_per']}%】，分销佣金【{$remark['order_commission']['commission_money']}】
佣金总计：【{$remark['commission_money']}】
TPL;
		return $remark_str;
	}
}